<!-- 库房管理---生产领料 -->
<script lang="ts">
export default {
  name: "pickingOut",
  components: {
    pickingOut
  }
};
</script>
<script setup lang="ts">
import { reactive, ref, nextTick, onMounted } from "vue";
import { changeHeight } from "/@/utils/public.mixin";
import pickingOut from "/@/views/wms/picking/pickingOut.vue";
import { VxeTableInstance } from "vxe-table";
import { getProcessAll } from "/@/api/basic/workprocedure";
import { queryPickBillPage } from "/@/api/wms/picking";
import { dateFormatYMD } from "/@/utils/date";
// import { queryProductOrderPage } from "/@/api/prm/productionOder";
import { queryItemByCodes } from "/@/api/basic/dictionaries";
import { queryMaterialPage } from "/@/api/basic/material";
import { alertMessage } from "/@/utils/message";
import { ElForm } from "element-plus";
import { useRoute } from "vue-router";

const route = useRoute();
const routeName = route.name as string;
const xTable = ref({} as VxeTableInstance);
// const xToolbar = ref({} as VxeToolbarInstance);
const page = reactive({
  pageNum: 1,
  pageRow: 20,
  totalResult: 0
});
const table = reactive({
  loading: false,
  tableData: [] as any[],
  tableHeight: 0, //表格高度
  listQuery: {
    cashingDate: "",
    productNo: "",
    bnoNo: "",
    finishFlag: "" as any,
    date: "" as any
  }
});

// 查询
const searchEvent = () => {
  const data: any = {};
  data.bnoNo = table.listQuery.bnoNo;
  data.pageNum = page.pageNum;
  data.pageRow = page.pageRow;
  data.productNo = table.listQuery.productNo;
  table.loading = true;
  data.finishFlag =
    table.listQuery.finishFlag === "" || table.listQuery.finishFlag == -1
      ? -1
      : table.listQuery.finishFlag;

  if (table.listQuery.date) {
    data.startTime = dateFormatYMD(table.listQuery.date[0]) + " 00:00:00";
    data.endTime = dateFormatYMD(table.listQuery.date[1]) + " 23:59:59";
  } else {
    data.startTime = "";
    data.endTime = "";
  }
  queryPickBillPage(data).then((res: any) => {
    if (res.code === 0) {
      table.tableData = res.data.list;
      page.totalResult = res.data.total;
    }
    table.loading = false;
  });
};
//获取工序名称
const getProcess = () => {
  getProcessAll().then((res: any) => {
    if (res.code === 0) {
      procedure.processData = res.data;
    }
  });
};
// 分页查询所有的货品
const getAllWh = (target: any) => {
  var str = "" as string;
  if (target && target.target.value) {
    str = target.target.value;
  }
  const data: any = {};
  Object.assign(data, table.listQuery);
  data.pageNum = page.pageNum;
  data.pageRow = page.pageRow;
  data.name = str;
  table.loading = true;
  queryMaterialPage(data).then((res: any) => {
    if (res.code === 0) {
      procedure.goodsData = res.data.list;
    }
  });
};
// 分页发生改变时会触发该事件
const handlePageChange = ({ currentPage, pageSize }) => {
  page.pageNum = currentPage;
  page.pageRow = pageSize;
  searchEvent();
};
// 添加
const procedure = reactive({
  loading: false,
  submitLoading: false,
  selectRow: null,
  showEdit: false,
  tableData: [] as any[],
  processData: [] as any[],
  goodsData: [] as any[],
  numberData: [] as any[], //存储数量单位信息
  orderData: [] as any[],
  idsDo: {
    ids: []
  },
  formData: {
    bnoNo: "",
    cashingDate: "",
    prodOrderId: "",
    prodOrderNo: "",
    materialPlanItems: [] as any[],
    processStepId: ""
  },
  formRules: {
    prodOrderId: [
      { required: true, message: "请选择生产订单编号", trigger: "blur" }
    ],
    processStepId: [{ required: true, message: "请选择工序", trigger: "blur" }]
  },
  picking: [
    { label: "是", value: 1 },
    { label: "否", value: 0 }
  ]
});

// const addRepair =  () => {
//   procedure.formData.materialPlanItems.push({
//     bomCode: "",
//     useNum: 0,
//     id: 0,
//     materialPlanId: 0,
//     bomId: "",
//     lengthUnit: "",
//     longt: "",
//     miscellaneousDeliveryId: 0,
//     quantityUnit: "",
//     measureUnit: "",
//     remark: "",
//     reqNum: 0,
//     specification: "",
//     thickness: "",
//     thicknessUnit: "",
//     weight: "",
//     weightUnit: "",
//     node: "",
//     width: "",
//     widthUnit: ""
//   });
// };
// 领料
// const insertEvent =  () => {
//   procedure.selectRow = null;
//   procedure.showEdit = true;
//   procedure.formData.cashingDate = dateFormatYMD(new Date()) + " 00:00:00";
//   addRepair();
//   queryUnit("数量");
// };

// 名称改变时的变化
// const proOrderChange = () => {
//   if (procedure.formData.prodOrderId) {
//     var arr = procedure.orderData.filter(
//       item => item.id == procedure.formData.prodOrderId
//     )[0];
//     procedure.formData.bnoNo = arr.bnoNo;
//     procedure.formData.prodOrderNo = arr.prodOrderNo;
//   } else {
//     procedure.formData.bnoNo = "";
//     procedure.formData.prodOrderNo = "";
//   }
// };

// 分页查询所有的货品
// const getAllProductOrder = (target: any) => {
//   var str = "" as string;
//   if (target && target.target.value) {
//     str = target.target.value;
//   }
//   const data: any = {};
//   Object.assign(data, table.listQuery);
//   data.pageNum = page.pageNum;
//   data.pageRow = page.pageRow;
//   data.prodOrderNo = str;
//   queryProductOrderPage(data).then((res: any) => {
//     if (res.code === 0) {
//       procedure.orderData = res.data.list;
//     }
//   });
// };
const checkRoleNameUnique = () => {
  var selectData = [];
  Object.keys(procedure.formData.materialPlanItems).forEach(key => {
    if (procedure.formData.materialPlanItems[key].name) {
      selectData.push(procedure.formData.materialPlanItems[key].name);
    }
  });
  if (new Set(selectData).size !== selectData.length) {
    alertMessage("当前有信息的编码或名称重复，请核对信息", "提示");
    return false;
  }
  return true;
};
// 入库表单提交
const insertForm = ref<InstanceType<typeof ElForm>>();

const submitEvent = () => {
  var bool = false;
  var bool1 = false;
  if (procedure.formData.materialPlanItems.length > 0) {
    for (var i = 0; i < procedure.formData.materialPlanItems.length; i++) {
      let data = procedure.formData.materialPlanItems[i];
      Object.keys(data).forEach(key => {
        if (key == "name" || key == "useNum") {
          data[key] === "" ? (bool = true) : null;
        }
        if (key == "useNum") {
          data[key] == 0 ? (bool1 = true) : null;
        }
      });
    }
    if (bool) {
      alertMessage("请将数据填写完整", "提示");
      return;
    }
    if (bool1) {
      alertMessage("备料数量不能为0", "提示");
      return;
    }
  } else {
    alertMessage("请填写详情信息", "提示");
    return;
  }
  if (!checkRoleNameUnique()) {
    return;
  }
  procedure.tableData = [];
  procedure.formData.materialPlanItems.map((item, index) => {
    procedure.tableData.push({
      bomCode: item.bomCode,
      cashingDate: procedure.formData.cashingDate,
      processStepId: procedure.formData.processStepId,
      prodOrderNo: procedure.formData.prodOrderNo,
      useNum: item.useNum
    });
  });
};
// 生产领料单---出库操作开始
const pickingItem = reactive({
  title: "", //标题
  subItemId: 0, //子项操作ID
  dialogShow: false, //子项操作显示隐藏
  readonly: false, //是否只读
  formShow: false //子项表单显示隐藏
});
// 查看详情操作
const pickingItemShow = (row: any) => {
  pickingItem.title = "查看详情";
  pickingItem.dialogShow = true;
  pickingItem.readonly = true;
  pickingItem.formShow = true;
  pickingItem.subItemId = row.id;
};
// 弹窗关闭
const pickingItemClose = () => {
  pickingItem.title = "";
  pickingItem.dialogShow = false;
  pickingItem.formShow = false;
  pickingItem.readonly = false;
  pickingItem.subItemId = 0;
};
// 查看
// const editEvent = (row: any) => {
//   procedure.showEdit = true;
//   Object.keys(procedure.formData).forEach(key => {
//     procedure.formData[key] = row[key] ? row[key] : procedure.formData[key];
//   });
//   getPickBillWithDetail(row.id).then((res: any) => {
//     procedure.formData = res.data;
//     procedure.formData.materialPlanItems = res.data.details;
//   });
// };
const handleClose = () => {
  nextTick(() => {
    procedure.formData = {
      bnoNo: "",
      cashingDate: "",
      prodOrderId: "",
      prodOrderNo: "",
      materialPlanItems: [] as any[],
      processStepId: ""
    };
    procedure.submitLoading = false;
    procedure.showEdit = false;
  });
};
// 获取数量单位
const queryUnit = (code: any) => {
  queryItemByCodes([code]).then((res: any) => {
    procedure.numberData = res;
  });
};
// mounted
onMounted(() => {
  nextTick(() => {
    // 将表格和工具栏进行关联
    searchEvent();
    getProcess();
    getAllWh("");
    queryUnit("数量");
    const $table = xTable.value;
    table.tableHeight = changeHeight();

    // const $toolbar = xToolbar.value;
    // $table.connect($toolbar);
  });
});
</script>
<template>
  <div>
    <!-- 工具栏 -->
    <vxe-form :data="table.listQuery">
      <vxe-form-item title="单号">
        <template #default="{ data }">
          <vxe-input v-model="data.bnoNo" placeholder="请输入单号"></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="生产订单编号">
        <template #default="{ data }">
          <vxe-input
            v-model="data.productNo"
            placeholder="请输入生产订单编号"
          ></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="制单日期" field="date">
        <template #default="{ data }">
          <el-date-picker
            v-model="data.date"
            size="small"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
          ></el-date-picker>
        </template>
      </vxe-form-item>
      <vxe-form-item title="状态" field="finishFlag">
        <template #default="{ data }">
          <el-select
            v-model="data.finishFlag"
            filterable
            clearable
            placeholder="请选择状态"
            size="small"
            style="width: 100%"
          >
            <el-option label="完成" :value="1">完成</el-option>
            <el-option label="待办" :value="0">待办</el-option>
          </el-select>
        </template>
      </vxe-form-item>
      <vxe-form-item>
        <template #default>
          <vxe-button
            icon="fa fa-search"
            status="primary"
            @click="searchEvent"
            v-auth="routeName + ':search'"
            >查询</vxe-button
          >
          <!-- <vxe-button
            icon="fa fa-plus"
            status="primary"
            @click="insertEvent"
            v-auth="routeName + ':add'"
            >新增</vxe-button
          > -->
        </template>
      </vxe-form-item>
    </vxe-form>
    <!-- 列表 -->
    <!-- <vxe-toolbar ref="xToolbar" style="margin: 12px 0 -12px 0" custom>
    </vxe-toolbar> -->
    <vxe-table
      ref="xTable"
      class="mytable-style"
      border
      show-header-overflow
      show-overflow
      :row-config="{ isHover: true }"
      :print-config="{}"
      :export-config="{}"
      :height="table.tableHeight"
      :data="table.tableData"
    >
      <vxe-column type="seq" title="序号" width="60"></vxe-column>
      <vxe-column field="bnoNo" title="单号" min-width="150"></vxe-column>
      <vxe-column
        field="classificationU9Name"
        title="单据类型"
        min-width="120"
      ></vxe-column>
      <vxe-column
        field="productNo"
        title="生产订单编号"
        min-width="180"
      ></vxe-column>
      <vxe-column
        field="deviceName"
        title="设备名称"
        min-width="160"
      ></vxe-column>
      <vxe-column field="userName" title="领料人" min-width="100"></vxe-column>
      <vxe-column field="createDate" title="制单日期" min-width="100">
        <template #default="{ row }">
          {{ row.createDate ? row.createDate.split(" ")[0] : "" }}
        </template>
      </vxe-column>
      <vxe-column title="是否领料" width="100">
        <template #default="{ row }">
          <el-tag type="success" v-if="row.confirmFlag == true">是</el-tag>
          <el-tag type="warning" v-if="row.confirmFlag == false">否</el-tag>
        </template>
      </vxe-column>
      <vxe-column title="状态" width="80">
        <template #default="{ row }">
          <el-tag type="success" v-if="row.finishFlag == 1">完成</el-tag>
          <el-tag type="warning" v-if="row.finishFlag == 0">待办</el-tag>
        </template>
      </vxe-column>
      <vxe-column title="操作" width="120" fixed="right">
        <template #default="{ row }">
          <vxe-button
            type="text"
            icon="fa fa-eye"
            @click="pickingItemShow(row)"
            v-auth="routeName + ':checkDetail'"
            >查看详情</vxe-button
          >
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <vxe-pager
      perfect
      @page-change="handlePageChange"
      v-model:current-page="page.pageNum"
      v-model:page-size="page.pageRow"
      :total="page.totalResult"
      :page-sizes="[10, 20, 50, 100, 300]"
      :layouts="[
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total'
      ]"
    >
    </vxe-pager>
    <!-- 领料弹框 -->
    <el-dialog
      v-model="procedure.showEdit"
      title="新增&保存"
      top="7vh"
      width="80%"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form
        ref="insertForm"
        :model="procedure.formData"
        :rules="procedure.formRules"
        label-align="right"
      >
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
            <el-form-item prop="prodOrderNo" label="生产订单编号">
              {{ procedure.formData.prodOrderNo }}
              <!-- <el-select
                v-model="procedure.formData.prodOrderId"
                filterable
                clearable
                placeholder="请选择"
                size="small"
                style="width: 100%"
                @keyup="getAllProductOrder"
                @clear="getAllProductOrder"
                @blur="getAllProductOrder"
                @focus="getAllProductOrder"
                @change="proOrderChange"
              >
                <el-option
                  v-for="item in procedure.orderData"
                  :key="item.id"
                  :label="item.prodOrderNo + '（' + item.bnoNo + '）'"
                  :value="item.id"
                >
                </el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
            <el-form-item prop="bnoNo" label="销售单号">
              {{ procedure.formData.bnoNo }}
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
            <el-form-item prop="cashingDate" label="备料时间">
              {{ procedure.formData.cashingDate }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        stripe
        :data="procedure.formData.materialPlanItems"
        border
        fit
        size="mini"
        highlight-current-row
        tooltip-effect="dark"
      >
        <el-table-column
          type="index"
          width="50"
          label="序号"
          fixed
        ></el-table-column>

        <el-table-column label="品名" prop="bomName">
          <template #default="scope">
            {{ scope.row.bomName }}
            <!-- <el-select
              v-model="scope.row.bomName"
              placeholder="请选择"
              style="width: 100%"
              size="small"
              @keyup="getAllWh"
              @clear="getAllWh"
              @change="codeChange(scope.row.name, scope.$index)"
            >
              <el-option
                v-for="item in procedure.goodsData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select> -->
          </template>
        </el-table-column>
        <el-table-column
          prop="bomCode"
          label="料号"
          min-width="120"
        ></el-table-column>
        <el-table-column
          prop="measureUnit"
          label="计量单位"
          width="100"
        ></el-table-column>
        <el-table-column label="长度(单位)" width="90">
          <template #default="{ row }">
            {{ row.longt
            }}{{
              row.longt && row.lengthUnit ? "(" + row.lengthUnit + ")" : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="宽度(单位)" width="90">
          <template #default="{ row }">
            {{ row.width
            }}{{ row.width && row.widthUnit ? "(" + row.widthUnit + ")" : "" }}
          </template>
        </el-table-column>
        <el-table-column label="厚度/高度(单位)" width="110">
          <template #default="{ row }">
            {{ row.thickness
            }}{{
              row.thickness && row.thicknessUnit
                ? "(" + row.thicknessUnit + ")"
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="规格"
          width="120"
          prop="specification"
        ></el-table-column>
        <el-table-column label="成本(单位)" width="80">
          <template #default="{ row }">
            {{ row.weight
            }}{{
              row.weight && row.weightUnit ? "(" + row.weightUnit + ")" : ""
            }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="备料数量" prop="useNum" width="200">
          <template #default="scope">
            <el-input-number
              size="small"
              v-model="scope.row.useNum"
              :min="0"
              :precision="2"
              :step="0.1"
              placeholder="请输入领取数量"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="数量单位" width="120">
          <template #default="{ row }">
            <el-select
              v-model="row.quantityUnit"
              filterable
              size="small"
              style="width: 100%"
              placeholder="请选择"
            >
              <el-option
                v-for="item in procedure.numberData"
                :key="item.id"
                :label="item.unitName"
                :value="item.unitName"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column> -->
        <el-table-column label="领料数量" prop="qty" width="200">
          <template #default="scope">
            {{ scope.row.qty }}
            <!-- <el-input-number
              size="small"
              v-model="scope.row.qty"
              :min="0"
              :precision="2"
              :step="0.1"
              placeholder="退料数量"
            ></el-input-number> -->
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <vxe-button @click="handleClose">取 消</vxe-button>
        <vxe-button status="primary" @click="submitEvent">确 定</vxe-button>
      </template>
    </el-dialog>
    <!-- 生产领料---查看详情操作 -->
    <picking-out
      :title="pickingItem.title"
      :subItemId="pickingItem.subItemId"
      :dialogShow="pickingItem.dialogShow"
      :formShow="pickingItem.formShow"
      :readonly="pickingItem.readonly"
      @pickingItemClose="pickingItemClose"
      @searchEvent="searchEvent"
    ></picking-out>
  </div>
</template>
<style scoped>
@import url("/@/style/dialog.css");
</style>
<style>
.mytable-style .vxe-body--column.col-blue {
  background-color: #60b8ff;
  color: #fff;
}
.mytable-style .vxe-body--column.col-orange {
  background-color: #f56c6c;
  color: #fff;
}
</style>
<style lang="scss" scoped>
.vxe-input + .vxe-button,
.vxe-input + .vxe-button--dropdown,
.vxe-button + .vxe-button,
.vxe-button + .vxe-button--dropdown {
  margin-left: 0;
}

.vxe-toolbar.size--medium {
  padding: 10px;
}

.vxe-table--render-default.size--medium {
  margin-top: 12px;
}

.vxe-button.size--medium.type--button {
  margin-left: 1em;
  height: 32px;
}

.text-model {
  &:hover {
    cursor: pointer;
  }
}
.codeBtn {
  width: 70px;
  height: 36px;
  background-color: dodgerblue;
  border-radius: 6px;
  color: #fff;
}

.codeBtn a {
  font-size: 16px;
  line-height: 40px;
  padding-left: 74px;
  color: #fff;
}
</style>
